package com.jd.user.service.impl;

import com.jd.basic.exception.BusinessException;
import com.jd.basic.service.impl.BaseServiceImpl;
import com.jd.basic.util.Md5Utils;
import com.jd.basic.util.StrUtils;
import com.jd.user.domain.Logininfo;
import com.jd.user.domain.User;
import com.jd.user.dto.UserDto;
import com.jd.user.mapper.LogininfoMapper;
import com.jd.user.mapper.UserMapper;
import com.jd.user.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    @Transactional
    public void phoneRegister(UserDto userDto) {
        String phone = userDto.getPhone();
        String phoneCode = userDto.getPhoneCode();
        String pwd = userDto.getPwd();
        String rePwd = userDto.getRePwd();
        // 1.空值校验
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(phoneCode)
                || StringUtils.isEmpty(pwd)|| StringUtils.isEmpty(rePwd)){
            throw  new BusinessException("信息不能为空!!!");
        }
        //2.两个密码是否相同校验
        if (!pwd.equals(rePwd)){
            throw  new BusinessException("两次密码不一致!!!");
        }
        //3.短信验证码校验
        // 获取register中的验证码
        Object codeObj = redisTemplate.opsForValue().get("register:" + phone);
        // 先判断验证码是否过期
        if (codeObj==null){
            throw  new BusinessException("手机验证码过期!!!");
        }
        // 在判断获取的验证码和前端输入传来的验证是否一致
        if(!codeObj.toString().split(":")[0].equals(phoneCode)){
            throw  new BusinessException("手机验证码错误!!!");
        }
        // 验证成功添加到数据库
        User user = userDto2User(userDto);
        Logininfo logininfo = user2Logininfo(user);
        // 先添加到logininfo中，获取自增id
        logininfoMapper.save(logininfo);
        // 在添加到user
        userMapper.save(user);
    }

    @Override
    @Transactional
    public void emailRegister(UserDto userDto) {
        String email = userDto.getEmail();
        String pwd = userDto.getPwd();
        String rePwd = userDto.getRePwd();
        // 1.空值校验
        if (StringUtils.isEmpty(email) || StringUtils.isEmpty(pwd)|| StringUtils.isEmpty(rePwd)){
            throw  new BusinessException("信息不能为空!!!");
        }
        // 验证账户是否存在
        User user1 = userMapper.loadByEmail(email);
        if (user1!=null){
            throw new BusinessException("已注册，请直接登录");
        }

        //2.两个密码是否相同校验
        if (!pwd.equals(rePwd)){
            throw  new BusinessException("两次密码不一致!!!");
        }
        // 验证成功添加到数据库
        User user = userDto2User(userDto);
        Logininfo logininfo = user2Logininfo(user);
        // 先添加到logininfo中，获取自增id
        logininfoMapper.save(logininfo);
        // 在添加到user
        userMapper.save(user);
    }


    private User userDto2User(UserDto userDto) {
        User user = new User();
        // 将userDto的属性添加到user中
        user.setUsername(userDto.getPhone());
        user.setPhone(userDto.getPhone());

        user.setUsername(userDto.getEmail());
        user.setEmail(userDto.getEmail());
        //获取userDto的盐值
        String salt = StrUtils.getComplexRandomString(32);
        user.setSalt(salt);
        // 加密
        String md5Pwd = Md5Utils.encrypByMd5(userDto.getPwd() + salt);
        user.setPassword(md5Pwd);
        user.setState(1);
        return user;
    }
    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        //按照属性同名原则
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);//用户
        logininfo.setDisable(true);
        return logininfo;
    }

    @Override
    @Transactional
    public void remove(Long id) {
        User user = userMapper.loadById(id);
        logininfoMapper.remove(user.getLogininfoId());

        super.remove(id);
    }

    @Override
    @Transactional
    public void update(User user) {
        // 先获取盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        super.update(user);
        // 获取登录信息的id

        Long logininfoId = userMapper.loadById(user.getId()).getLogininfoId();
        // 通过id获取注册的信息
        Logininfo logininfo = logininfoMapper.loadById(logininfoId);
        //将新的数据覆盖旧的数据
        BeanUtils.copyProperties(user,logininfo);//5个数据新的 - 用户名，邮箱，电话，盐值，密码
        logininfoMapper.update(logininfo);

    }

    @Override
    @Transactional
    public void save(User user) {
        //处理盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);

        //保存logininfo
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        logininfoMapper.save(logininfo);

        //保存user
        user.setLogininfoId(logininfo.getId());
        super.save(user);
    }
}
